package com.jiawa.train.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiawa.train.business.domain.DailyTrain;
import com.jiawa.train.business.domain.Train;
import com.jiawa.train.business.mapper.DailyTrainMapper;
import com.jiawa.train.business.req.DailyTrainQueryReq;
import com.jiawa.train.business.req.DailyTrainSaveReq;
import com.jiawa.train.business.resp.DailyTrainQueryResp;
import com.jiawa.train.business.service.DailyTrainService;
import com.jiawa.train.business.service.DailyTrainStationService;
import com.jiawa.train.business.service.DailyTrainCarriageService;
import com.jiawa.train.business.service.DailyTrainSeatService;
import com.jiawa.train.business.service.DailyTrainTicketService;
import com.jiawa.train.business.service.TrainService;
import com.jiawa.train.common.resp.PageResp;
import com.jiawa.train.common.util.SnowUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class DailyTrainServiceImpl extends ServiceImpl<DailyTrainMapper, DailyTrain> implements DailyTrainService {
    private static final Logger LOG = LoggerFactory.getLogger(DailyTrainServiceImpl.class);

    @Resource
    private TrainService trainService;
    @Resource
    private DailyTrainStationService dailyTrainStationService;
    @Resource
    private DailyTrainCarriageService dailyTrainCarriageService;
    @Resource
    private DailyTrainSeatService dailyTrainSeatService;
    @Resource
    private DailyTrainTicketService dailyTrainTicketService;


    public void save(DailyTrainSaveReq req) {
        DateTime now = DateTime.now();
        DailyTrain dailyTrain = BeanUtil.copyProperties(req, DailyTrain.class);
        if (ObjectUtil.isNull(dailyTrain.getId())) {
            dailyTrain.setId(SnowUtil.getSnowflakeNextId());
            dailyTrain.setCreateTime(now);
            dailyTrain.setUpdateTime(now);
            this.save(dailyTrain);
        } else {
            dailyTrain.setUpdateTime(now);
            this.updateById(dailyTrain);
        }
    }

    public PageResp<DailyTrainQueryResp> queryList(DailyTrainQueryReq req) {
        LambdaQueryWrapper<DailyTrain> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(DailyTrain::getDate)
                .orderByAsc(DailyTrain::getCode);
        if (ObjectUtil.isNotEmpty(req.getDate())) {
            wrapper.eq(DailyTrain::getDate, req.getDate());
        }
        if (ObjectUtil.isNotEmpty(req.getCode())) {
            wrapper.eq(DailyTrain::getCode, req.getCode());
        }
        LOG.info("查询页码：{}", req.getPage());
        LOG.info("每页条数：{}", req.getSize());
        Page<DailyTrain> page = new Page<>(req.getPage(), req.getSize());
        Page<DailyTrain> dailyTrainPage = this.page(page, wrapper);
        LOG.info("总行数：{}", dailyTrainPage.getTotal());
        LOG.info("总页数：{}", dailyTrainPage.getPages());
        List<DailyTrainQueryResp> list = BeanUtil.copyToList(dailyTrainPage.getRecords(), DailyTrainQueryResp.class);
        PageResp<DailyTrainQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(dailyTrainPage.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    public void delete(Long id) {
        this.removeById(id);
    }

    /**
     * 生成某日所有车次信息，包括车次、车站、车厢、座位
     * @param date
     */

    public void genDaily(Date date) {
        List<Train> trainList = trainService.selectAll();
        //遇到集合有习惯的取查空
        if(CollUtil.isEmpty(trainList)){
            LOG.info("没有车次基础数据，任务结束");
            return;
        }
        LOG.info("生成日期[{}]的车次信息开始", DateUtil.formatDate(date));
        for (Train train : trainList) {
            genDailyTrain(date, train);
        }
        LOG.info("生成日期[{}]的车次信息结束", DateUtil.formatDate(date));
    }

    @Transactional
    public void genDailyTrain(Date date, Train train) {
        LOG.info("生成日期[{}]车次[{}]的信息开始", DateUtil.formatDate(date), train.getCode());
        LambdaQueryWrapper<DailyTrain> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DailyTrain::getDate, date)
                .eq(DailyTrain::getCode, train.getCode());
        this.remove(wrapper);
        DateTime now = DateTime.now();
        DailyTrain dailyTrain = new DailyTrain();
        dailyTrain.setId(SnowUtil.getSnowflakeNextId());
        dailyTrain.setDate(date);
        dailyTrain.setCode(train.getCode());
        dailyTrain.setType(train.getType());
        dailyTrain.setStart(train.getStart());
        dailyTrain.setStartPinyin(train.getStartPinyin());
        dailyTrain.setStartTime(train.getStartTime());
        dailyTrain.setEnd(train.getEnd());
        dailyTrain.setEndPinyin(train.getEndPinyin());
        dailyTrain.setEndTime(train.getEndTime());
        dailyTrain.setCreateTime(now);
        dailyTrain.setUpdateTime(now);
        this.save(dailyTrain);
        //生成车次的信息

        //生成的车站信息
        dailyTrainStationService.genDaily(date, train.getCode());
        //生成车厢
        dailyTrainCarriageService.genDaily(date, train.getCode());
        //生成
        dailyTrainSeatService.genDaily(date, train.getCode());

        dailyTrainTicketService.genDaily(dailyTrain,date, train.getCode());
        LOG.info("生成日期[{}]车次[{}]的信息结束", DateUtil.formatDate(date), train.getCode());
    }

    public List<DailyTrain> selectByDate(Date date) {
        LambdaQueryWrapper<DailyTrain> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DailyTrain::getDate, date)
                .orderByAsc(DailyTrain::getCode);
        return this.list(wrapper);
    }
} 